<template>
	<view class="page">
		<view class="coupon-list">
			<view v-if="coupons.list.length">
				<view class="coupon" v-for="(item, index) of coupons.list" :key="index">
					<view class="coupon_left">
						<view class="amount-box">
							<view class="count">{{ item.subMoney }}</view>
							<view class="unit">{{ item.type === 1 ? '元' : '折' }}</view>
						</view>
						<view class="desc-box">
							<view class="name up-line-1">{{ item.name }}</view>
							<view class="time up-line-2">{{ `共${item.totalNum}张` }}
								<span v-if="item.personLimited">,{{ `每人限领${item.personNum}张` }}</span>
							</view>
						</view>
					</view>
					<view class="coupon_right">
						<view class="btn" @click="handleCollect(item.uuid)" v-if="token && token !== ''"></view>
						<view class="btn" @click="handleLogin" v-else></view>
					</view>
				</view>
				<up-loadmore status="nomore" nomore-text="没有更多了" fontSize="12" color="#909399" />
			</view>
			<up-empty mode="coupon" iconColor="#EBEEF5" marginTop="100" v-else></up-empty>
		</view>
		<!-- 登录弹窗 -->
		<LoginPopup ref="loginPopupRef" @success="handleLoginSuccess" />
		<!-- 领取成功 -->
		<up-modal
			:show="showModal"
			closeOnClickOverlay
			showCancelButton
		>
			<template>
				<view class="text-center">领取成功，快去使用吧！</view>
			</template>
			<template #confirmButton>
				<up-button
					text="去使用"
					type="success"
					shape="circle"
					color="#D19973"
					@click="toUse"
				></up-button>
			</template>
		</up-modal>
	</view>
</template>

<script setup>
	import {
		ref,
		reactive
	} from 'vue'
	import {
		onLoad,
		onShareAppMessage,
		onShareTimeline
	} from '@dcloudio/uni-app'
	import {
		timeFormat
	} from '@/uni_modules/uview-plus';
	import uma from '../../uma.js';
	
	const showModal = ref(false)
	// 运维人员
	const oper = ref(null)
	// 获取token
	const token = ref(null)
	// 每次扫码可领取的次数
	const counts = ref(0)
	// 已领取次数
	const collect_counts = ref(0)
	onLoad((option) => {
		token.value = uni.getStorageSync('token')
		counts.value = option.time ? Number(option.time) : 0
		oper.value = option.oper
		getCouponTask()
		
		// 上报微信数据管理
		// #ifdef MP-WEIXIN
		const updateData = {
			oper: option.oper,
			coupon_count: option.time,
			open_time: timeFormat(new Date().getTime(), 'yyyy-mm-dd hh:MM:ss')
		}
		upWxData(updateData)
		// #endif
	})
	
	// 登录
	const loginPopupRef = ref(null)
	function handleLogin() {
		loginPopupRef.value.open()
	}
	function handleLoginSuccess() {
		uni.showToast({
			icon: 'success',
			title: '登录成功'
		})
		token.value = uni.getStorageSync('token')
	}

	// 优惠券
	const coupons = reactive({
		list:  [],
	})

	// 获取待领取优惠券
	function getCouponTask() {
		uni.showLoading()
		uni.request({
			url: `${getApp().globalData.baseUrl}/prod-api/coupons/to/take/list/anonymous`,
			method: 'GET',
			data: {
				pageNum: 1,
				pageSize: 9999
			},
			success: (res) => {
				if (res.data.code === 200) {
					coupons.list = res.data.rows
					uni.hideLoading()
				}
			},
			fail: (error) => {
				console.log(error);
			}
		});
	}

	/**
	 * 领取优惠券 
	 * 若有限制每次领取的次数限制，前提是优惠券无限制领取次数，则判断领取次数与限制次数关系
	 * 若无限制，则直接请求接口
	*/
	function handleCollect(uuid) {
		if (counts.value) {
			if (collect_counts.value >= counts.value) {
				uni.showToast({
					icon: 'none',
					title: '已经领完啦~'
				})
				return
			}
		}
		uni.request({
			url: `${getApp().globalData.baseUrl}/prod-api/coupons/task/${uuid}`,
			method: 'GET',
			header: {
				'Authorization': "Bearer " + token.value,
			},
			success: (res) => {
				if (res.data.code === 200) {
					collect_counts.value += 1
					showModal.value = true
				} else {
					uni.showToast({
						icon: 'none',
						title: res.data.msg
					})
				}
			},
			fail: (error) => {
				console.log(error);
			}
		});
	}
	
	// 上报微信管理数据
	function upWxData(data) {
		wx.reportEvent('oper_time', data)
		// #ifdef MP-WEIXIN
		uma.trackEvent('oper_time', data)
		// #endif
	}
	
	// 分享
	onShareAppMessage(res => {
		let path = '/pages/coupon/list'
		if (oper.value) {
			path += `?oper=${oper.value}&time=${counts.value}`
		}
		return {
			title: '领取优惠券',
			path
		}
	})
	
	// 分享到朋友圈
	onShareTimeline(res => {
		let path = '/pages/coupon/list'
		if (oper.value) {
			path += `?oper=${oper.value}&time=${counts.value}`
		}
		return {
			title: '领取优惠券',
			path
		}
	})
	
	// 去使用
	function toUse() {
		uni.reLaunch({
			url: '/pages/index/index'
		})
	}
</script>

<style lang="scss" scoped>
	.coupon-list {
		padding: 20rpx 30rpx;
		.coupon {
			width: 690rpx;
			height: 230rpx;
			background: url('https://gamumu.hilumo.com/prod-api/files/down/1954399569506119680.png') no-repeat;
			background-size: contain;
			margin-bottom: 10rpx;
			overflow: hidden;
			.coupon_left {
				float: left;
				width: 510rpx;
				height: 210rpx;
				border-radius: 115rpx;
				margin-top: 10rpx;
				padding-left: 40rpx;
				box-sizing: border-box;
				.amount-box {
					float: left;
					width: 200rpx;
					text-align: center;
					.count {
						font-size: 34px;
						margin-right: 8rpx;
						line-height: 210rpx;
						font-weight: 600;
						color: #D19973;
						display: inline-block;
					}
					
					.unit {
						font-size: 12px;
						line-height: 230rpx;
						color: #D19973;
						display: inline-block;
					}
				}
				.desc-box {
					padding-left: 10rpx;
					float: left;
					width: 270rpx;
					box-sizing: border-box;
					.name {
						font-size: 16px;
						font-weight: 600;
						margin-bottom: 20rpx;
						margin-top: 50rpx;
						color: #D19973;
					}
					.time {
						font-size: 12px;
						color: #D19973;
						opacity: 0.8;
					}
				}
			}
			.coupon_right {
				float: right;
				width: 180rpx;
				height: 230rpx;
				position: relative;
				.btn {
					width: 140rpx;
					height: 140rpx;
					left: 50%;
					top: 50%;
					margin-top: -70rpx;
					margin-left: -70rpx;
					border-radius: 70rpx;
					position: absolute;
				}
			}
		}
	}
</style>